from openai import OpenAI
from typing import List, Tuple
import time
import threading
import concurrent.futures

# 共享列表和锁
output_list = []
lock = threading.Lock()
client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"  # 根据服务配置调整
)



def ask_questions(client: OpenAI, model: str = "Qwen3-8B") -> List[Tuple[str, str]]:
    results = []
    idx = 0 
    context_str = ""  # 用于保存上下文的字符串 
    file_path = "test1.txt"

    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line_number, line in enumerate(file, start=1):
                line = line.strip()
                if not line:
                    continue

                try:
                    system, user = line.split('|', 1)
                except ValueError:
                    print(f"跳过第 {line_number} 行：格式不正确（缺少 '|' 分隔符）")
                    continue

                # 构造完整的 prompt，包含上下文
                full_prompt = f"以下是之前的对话历史：\n{context_str}\n\n当前问题：{user.strip()}"
                messages = [
                    {"role": "system", "content": system.strip()},
                    {"role": "user", "content": full_prompt}
                ]

                try:
                    start_time = time.time() 
                    response = client.chat.completions.create(
                        model=model,
                        messages=messages
                    )
                    answer = response.choices[0].message.content.strip()
                    idx = idx+1
                    end_time = time.time()
                    elapsed = end_time - start_time
                    print(f"[问题 {idx}] 响应长度: {len(answer)}, 耗时: {elapsed:.2f}秒")
                    result_string = f"[问题 {idx}] 响应长度: {len(answer)}, 耗时: {elapsed:.2f}秒"
                    with lock:  # 使用锁确保线程安全
                      output_list.append(result_string)
                    # 更新上下文字符串
                    context_str += f"User: {user.strip()}\nAssistant: {answer}\n"
                    results.append((user.strip(), answer))
                except Exception as e:
                    print(f"处理第 {line_number} 行时出错：{e}")
                    results.append((user.strip(), f"错误: {str(e)}"))

    except FileNotFoundError:
        print(f"错误：文件 {file_path} 不存在")
    except Exception as e:
        print(f"读取文件时出错：{e}")

    return results



# 并发测试函数
def run_concurrent_test(concurrency):
    """
    执行并发测试
    :param concurrency: 并发数量
    :return: 测试结果列表
    """
    results1 = []  # 用于存储每个请求的结果
    # 使用 ThreadPoolExecutor 管理线程池
    with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as executor:
        # 提交并发任务
        futures = [executor.submit(ask_questions,client) for i in range(concurrency)]

        # 遍历已完成的 Future 对象，获取结果
    """            # 遍历已完成的 Future 对象，获取结果
        for future in concurrent.futures.as_completed(futures):
            try:
                result1 = future.result()  # 获取 Future 的结果
                if result1:
                    results1.append(result)  # 将结果添加到列表中
            except Exception as e:
                print(f"An error occurred: {e}")
   """

if __name__ == "__main__":
    CONCURRENCY = 2  # 设置并发数量
    print(f"Starting concurrent test with {CONCURRENCY} threads...")

    # 执行并发测试
    file_path = "test1.txt"
    test_results = run_concurrent_test(CONCURRENCY)
# 调用函数
for item in output_list:
        print("AAA",item)
